import { useLocalStorage } from '@/biz/hooks/useLocalStorage'
import axios from 'axios'
import { showDialog } from 'vant'

const instance = axios.create({
  baseURL: '/api'
})

//在拦截器里面发送请求的时候把token的值传入
instance.interceptors.request.use((config) => {
  const { value: $tokenValue } = useLocalStorage('token', '')
  if (config.headers && $tokenValue.value) {
    config.headers['x-token'] = $tokenValue.value
  }
  return config
})

//添加拦截器(拦截器这边需要配合接口返回的固定参数或状态码来做)
instance.interceptors.response.use(
  (response) => {
    //为什么_data 是声明的变量名，即吧response返回的data数据赋值给_data
    const { data: _data } = response
    const { data, code, msg } = _data
    if (code !== 0) {
      showDialog({
        message: msg
      }).then(() => {
        //关闭弹窗
      })
      return Promise.reject(data)
    }
    return data
  },
  (err) => {
    if (err.response && err.response.status === 401) {
      showDialog({
        message: '页面过期，请重新登录'
      }).then(() => {
        location.href = '/login'
      })
    }
  }
)

export default instance
